import React, { useRef, useState } from 'react';
import { Input, Space, Button, Image } from 'antd';
import { useHistory } from 'react-router-dom';
import { add } from './../../api/banner'; // 引入添加轮播图接口

const width = { width: '300px' };

function Index() {
  const [link, setLink] = useState('');
  const [alt, setAlt] = useState('');
  const [img, setImg] = useState('');

  // 编程式导航
  const history = useHistory();

  const fileRef = useRef();

  const selectBanner = () => {
    console.log(fileRef.current.input);
    fileRef.current.input.click();
  };

  const getBanenrInfo = (e) => {
    const file = fileRef.current.input.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      setImg(this.result);
    };
  };

  const changeLink = (e) => {
    console.log(e.target);
    setLink(e.target.value);
  };

  const changeAlt = (e) => {
    console.log(e.target);
    setAlt(e.target.value);
  };

  const submitBanner = () => {
    const params = { img, link, alt };
    console.log(params);
    // 调用接口
    add(params).then((res) => {
      history.push('/banner/list');
    });
  };

  return (
    <Space direction='vertical'>
      <Input placeholder='link' style={width} value={link} onChange={changeLink} />
      <Input placeholder='alt' style={width} value={alt} onChange={changeAlt} />
      <Input style={width} hidden value={img} />
      <Input type='file' hidden ref={fileRef} onChange={getBanenrInfo}></Input>
      <Button onClick={selectBanner}>点击选择上传文件</Button>
      <Image height={300} src={img === '' ? 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png' : img} />
      <Button type='primary' disabled={img === ''} onClick={submitBanner}>
        提交
      </Button>
    </Space>
  );
}

export default Index;
